/**
 * 
 */
package dbAccess;

import java.sql.*;
import java.util.*;
import java.util.Map.Entry;

import exceptions.*;

import model.*;

/**
 * @author Anthares
 *
 */
public class AppSettingsDBAccess {
	public HashMap<AppSettingsEnum, AppSettings> loadAppSettings() throws DatabaseErrorException, PasIdentificationException{
		Connection conn = DBConnexionSingleton.getInstance();
		PreparedStatement stat;
		HashMap<AppSettingsEnum, AppSettings> appSet = new HashMap<AppSettingsEnum, AppSettings>();
		String query = "select * from app_settings;";
		try{
			stat = conn.prepareStatement(query);
			ResultSet data = stat.executeQuery();
			while(data.next()){
				appSet.put(AppSettingsEnum.valueOf(data.getInt("setting")), new AppSettings(data.getString("name"), data.getDouble("value")));
			}
			stat.close();
			
		}catch (SQLException e) {
			throw new DatabaseErrorException(e);
		}
		return appSet;
	}
	public void saveAppSettings(HashMap<AppSettingsEnum, AppSettings> appSet) throws DatabaseErrorException, PasIdentificationException, InvalidSettingException{
		Set<Entry<AppSettingsEnum,AppSettings>> settings = appSet.entrySet();
		HashMap<AppSettingsEnum, AppSettings> oldSettings = this.loadAppSettings();
		Connection conn = DBConnexionSingleton.getInstance();
		PreparedStatement stat;
		String query = "update app_settings set value = ? where setting = ?;";
		
		for(Entry<AppSettingsEnum, AppSettings> setting: settings){
			if(oldSettings.containsKey(setting.getKey())){
				AppSettingsEnum settingKey = setting.getKey();
				double settingValue = setting.getValue().getValue();
				if(settingValue!=oldSettings.get(settingKey).getValue()){
					try {
						stat = conn.prepareStatement(query);
							stat.setDouble(1, settingValue);
							stat.setInt(2, settingKey.getID());
						stat.executeUpdate();
					} catch (SQLException e) {
						throw new DatabaseErrorException(e);
					}
				}
			}else{
				throw new InvalidSettingException();
			}
		}
		
	}
}
